package business

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/business"
	businessReq "github.com/flipped-aurora/gin-vue-admin/server/model/business/request"
	businessRes "github.com/flipped-aurora/gin-vue-admin/server/model/business/response"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/response"
	"github.com/flipped-aurora/gin-vue-admin/server/service"
	"github.com/flipped-aurora/gin-vue-admin/server/utils"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"go.uber.org/zap"
)

type ClassifyApi struct {
}

var classifyService = service.ServiceGroupApp.BusinessServiceGroup.ClassifyService

// CreateClassify 创建企业分类
// @Tags Classify
// @Summary 创建企业分类
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body business.Classify true "创建企业分类"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"创建成功"}"
// @Router /classify/createClassify [post]
func (classifyApi *ClassifyApi) CreateClassify(c *gin.Context) {
	var classify business.Classify
	err := c.ShouldBindJSON(&classify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	verify := utils.Rules{
		"Name": {utils.NotEmpty()},
	}
	if err := utils.Verify(classify, verify); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	//当不是管理员时
	if isAdmin == 2 {
		classify.UserId = userId
	}
	reclassify, err := classifyService.GetClassifyByName(classify.UserId, classify.Name)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
		return
	}
	if reclassify.ID != 0 {
		response.FailWithMessage("该名称的分类已经存在", c)
		return
	}
	if err := classifyService.CreateClassify(&classify); err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败", c)
	} else {
		response.OkWithMessage("创建成功", c)
	}
}

// DeleteClassify 删除企业分类
// @Tags Classify
// @Summary 删除企业分类
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body business.Classify true "删除企业分类"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /classify/deleteClassify [delete]
func (classifyApi *ClassifyApi) DeleteClassify(c *gin.Context) {
	var classify business.Classify
	err := c.ShouldBindJSON(&classify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	//当不是管理员时
	if isAdmin == 2 {
		classify.UserId = userId
	}
	if err := classifyService.DeleteClassify(classify); err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

// DeleteClassifyByIds 批量删除企业分类
// @Tags Classify
// @Summary 批量删除企业分类
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除企业分类"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /classify/deleteClassifyByIds [delete]
func (classifyApi *ClassifyApi) DeleteClassifyByIds(c *gin.Context) {
	var IDS request.IdsReq
	err := c.ShouldBindJSON(&IDS)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	var userIdInfo uint
	//当不是管理员时
	if isAdmin == 2 {
		userIdInfo = userId
	}
	if err := classifyService.DeleteClassifyByIds(IDS, userIdInfo); err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败", c)
	} else {
		response.OkWithMessage("批量删除成功", c)
	}
}

// UpdateClassify 更新企业分类
// @Tags Classify
// @Summary 更新企业分类
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body business.Classify true "更新企业分类"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /classify/updateClassify [put]
func (classifyApi *ClassifyApi) UpdateClassify(c *gin.Context) {
	var classifyUpdate businessReq.ClassifyUpdate
	err := c.ShouldBindJSON(&classifyUpdate)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	verify := utils.Rules{
		"Name": {utils.NotEmpty()},
	}
	if err := utils.Verify(classifyUpdate, verify); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	//赋值
	var classify business.Classify
	err = copier.Copy(&classify, &classifyUpdate)
	if err != nil {
		global.GVA_LOG.Error("赋值时发生错误!", zap.Error(err))
		response.FailWithMessage("赋值时发生错误", c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)
	//管理员判断
	if isAdmin == 2 {
		classify.UserId = userId
	}
	reclassify, err := classifyService.GetClassifyByName(classify.UserId, classify.Name)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
		return
	}
	if reclassify.ID != classify.ID {
		response.FailWithMessage("该名称的分类已经存在", c)
		return
	}
	if err := classifyService.UpdateClassify(classify); err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// FindClassify 用id查询企业分类
// @Tags Classify
// @Summary 用id查询企业分类
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query business.Classify true "用id查询企业分类"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /classify/findClassify [get]
func (classifyApi *ClassifyApi) FindClassify(c *gin.Context) {
	var classify business.Classify
	err := c.ShouldBindQuery(&classify)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	isAdmin := utils.GetUserIsAdmin(c)
	userId := utils.GetUserID(c)

	//管理员判断
	if isAdmin == 2 {
		classify.UserId = userId
	}
	reclassify, err := classifyService.GetClassify(classify.ID, classify.UserId)
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
		return
	}
	if reclassify.ID == 0 {
		response.FailWithMessage("没有该数据", c)
		return
	}
	response.OkWithData(gin.H{"reclassify": reclassify}, c)
}

// GetClassifyList 分页获取企业分类列表
// @Tags Classify
// @Summary 分页获取企业分类列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query businessReq.ClassifySearch true "分页获取企业分类列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /classify/getClassifyList [get]
func (classifyApi *ClassifyApi) GetClassifyList(c *gin.Context) {
	var pageInfo businessReq.ClassifySearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	userId := utils.GetUserID(c)
	pageInfo.UserId = userId
	list, _, err := classifyService.GetClassifyInfoList(pageInfo)
	if err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	}
	//查询
	response.OkWithDetailed(gin.H{"list": list}, "获取成功", c)
}

// AdminGetClassifyList 管理员分页获取企业分类列表
// @Tags Classify
// @Summary 分页获取企业分类列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query businessReq.ClassifySearch true "分页获取企业分类列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /classify/adminGetClassifyList [get]
func (classifyApi *ClassifyApi) AdminGetClassifyList(c *gin.Context) {
	//判断是否是管理员，根据不同身份返回不同的值
	isAdmin := utils.GetUserIsAdmin(c)
	var pageInfo businessReq.ClassifySearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if isAdmin == 1 {
		list, total, err := classifyService.GetClassifyInfoList(pageInfo)
		if err != nil {
			global.GVA_LOG.Error("获取失败!", zap.Error(err))
			response.FailWithMessage("获取失败", c)
			return
		}
		//赋值
		var classifyAdminQueryList []businessRes.ClassifyAdminQuery
		err = copier.Copy(&classifyAdminQueryList, &list)
		if err != nil {
			global.GVA_LOG.Error("赋值时发生错误!", zap.Error(err))
			response.FailWithMessage("赋值时发生错误", c)
			return
		}

		//附带用户信息
		//定义用户数组
		var userIdList []uint
		for _, v := range classifyAdminQueryList {
			userIdList = append(userIdList, v.UserId)
		}
		userList, err := userService.FindUserByIdList(userIdList)
		if err != nil {
			global.GVA_LOG.Error("获取用户信息失败!", zap.Error(err))
			response.FailWithMessage("获取用户信息失败", c)
		}
		//定义用户map
		userMap := make(map[uint]businessRes.UserInfo)
		for _, v := range userList {
			userMap[v.ID] = businessRes.UserInfo{
				ID:       v.ID,
				NickName: v.NickName,
				Username: v.Username,
			}
		}

		for k, v := range classifyAdminQueryList {
			classifyAdminQueryList[k].UserInfo = userMap[v.UserId]
		}

		response.OkWithDetailed(response.PageResult{
			List:     classifyAdminQueryList,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	} else {
		response.FailWithMessage("你没有权限", c)
	}
}
